import { createRouter, createWebHistory } from 'vue-router'
import LoginVue from '../view/Login.vue'
import RegisterVue from '../view/Register.vue'
import ResetPasswordVue from '../view/resetPassword.vue'
import MainVue from '../view/Main.vue'
import LibraryVue from '../view/library.vue'

const routes = [
  { path: '/', redirect: '/login' },
  {
    path: '/login',
    component: LoginVue,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    component: RegisterVue,
    meta: { requiresAuth: false }
  },
  {
    path: '/resetPassword',
    component: ResetPasswordVue,
    meta: { requiresAuth: false }
  },
  {
    path: '/main',
    component: MainVue,
    meta: { requiresAuth: true }
  },
  {
    path: '/library/:robotId',
    name: 'library',
    component: LibraryVue,
    metaL: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: routes
})

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const token = sessionStorage.getItem('user');

  // 3. 核心逻辑：需要登录但无 token → 跳登录页；否则正常跳转
  if (requiresAuth && !token) {
    next('/login'); // 未登录，强制跳登录
  } else {
    next(); // 已登录或无需登录，正常进入目标路由
  }
})

export default router;